package com.gvsoft.communication.net.gather;

import com.gvsoft.communication.console.IControl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:MService
 * Author: zhaoqiubo
 * Date: 15/11/11
 * Time: 上午9:51
 * Desc: 服务端并发情况收集器
 */
public class ConcurrentGather implements IControl {

    private final static Logger logger = LogManager.getLogger("net");
    ConcurrentCounter concurrentCounter = null;
    private static AtomicInteger readCount = new AtomicInteger(0);
    private static AtomicInteger writeCount = new AtomicInteger(0);

    private Integer concurrentReadCount;
    private Integer concurrentWriteCount;

    public ConcurrentGather() {
        if (null == concurrentCounter) {
            concurrentCounter = new ConcurrentCounter("ConcurrentCounter");
            concurrentCounter.start();
        }
    }

    public static void increasingRead() {
        readCount.incrementAndGet();

    }

    public static void increasingWrite() {
        writeCount.incrementAndGet();
    }

    public Integer getAvgReadCount() {
        return concurrentReadCount;
    }

    public Integer getAvgWriteCount() {
        return concurrentWriteCount;
    }

    @Override
    public String execute() {
        String statusStr;
        statusStr = "并发状态收集器打印结果如下:\r\n" + "每秒读取包(包含通讯层):" + getAvgReadCount() + "\r\n" +
                "每秒写入包(包含通讯层):" + getAvgWriteCount() + "\r\n";
        return statusStr;
    }

    @Override
    public void close() throws IOException {
        concurrentCounter.interrupt();
    }

    class ConcurrentCounter extends Thread {

        ConcurrentCounter(String name) {
            super(name);
        }

        private boolean flag = true;

        @Override
        public void interrupt() {
            this.flag = false;
            super.interrupt();
        }

        @Override
        public void run() {
            Integer cycle = 10;
            while (flag) {
                concurrentReadCount = readCount.get() / cycle;
                concurrentWriteCount = writeCount.get() / cycle;
                readCount.set(0);
                writeCount.set(0);
                try {
                    Thread.sleep(cycle * 1000);
                } catch (InterruptedException e) {
                    logger.info(this.getName() + "线程已经被中止!");
                }
            }
        }
    }
}
